<?php

class SkinController extends AbstractController {
	
	public $_skinPath;
	public $_cachePath;
	public $_config;
	
	public function preDispatch() {
		$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/minify.ini', 'production');
		
		$this->_skinPath = $this->getBasePath() . '/skin/';
		$this->_config = $config->minify->toArray();
		
		if (!is_dir($this->_skinPath))
			mkdir($this->_skinPath, 0777, true);
	}
	
	public function indexAction() {}
	
	public function cssAction() {
		header('Content-type: text/css');
		
		$section = $this->getRequest()->getParam('section', false);
		$page = $this->getRequest()->getParam('page', false);
		if (!$page) exit;
		
		$cache = CachePlugin::init();
		$name = 'css_'.$section.'_'.str_replace('-', '_', $page);
		if (($formatted = $cache->load($name)) === false) {
			$css = '';
			$path = $this->_config['css']['path'][$section];
			$array = $this->_config['css'][$section];
			
			if ($array) {
				if ($page == 'galeria')
					unset($array[4]);
				
				if (file_exists($this->_skinPath . ($path ? $path . '/' : '') . 'css/' . $page . '.css'))
					$array[] = ($path ? $path . '/' : '') . 'css/' . $page;
					
				foreach ($array as $file) {
					$css .= file_get_contents($this->_skinPath . $file . '.css');
				}
				
				$formatted = $css;
				
				// $cache->save($formatted, $name);
			}
		}
		
		die($formatted);
	}
	
	public function jsAction() {
		header('Content-type: text/javascript; charset=UTF-8');
		
		$section = $this->getRequest()->getParam('section', false);
		$page = $this->getRequest()->getParam('page', false);
		if (!$page) exit;
		
		$cache = CachePlugin::init();
		$name = 'js_'.$section.'_'.str_replace('-', '_', $page);
		if (($formatted = $cache->load($name)) === false) {
			$js	= '';
			$path = $this->_config['js']['path'][$section];
			$array = $array = $this->_config['js'][$section];
			
			if ($array) {
				if (file_exists($this->_skinPath . ($path ? $path . '/' : '') . 'js/' . $page . '.js'))
					$array[] = ($path ? $path . '/' : '') . 'js/' . $page;
				
				foreach ($array as $file)
					$js .= file_get_contents($this->_skinPath . $file . '.js');
				
				$formatted = $js;
				
				// $cache->save($formatted, $name);
			}
		}
		
		die($formatted);
	}
}